/**
 *  Copyright (c) 1997-2013, www.tinygroup.org (luo_guo@icloud.com).
 *
 *  Licensed under the GPL, Version 3.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *       http://www.gnu.org/licenses/gpl.html
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */

package com.xnck.maventest.dao;

import static org.tinygroup.tinysqldsl.base.StatementSqlBuilder.and;
import static com.xnck.maventest.dao.UserTable.*;
import static org.tinygroup.tinysqldsl.Select.*;
import static org.tinygroup.tinysqldsl.Insert.*;
import static org.tinygroup.tinysqldsl.Delete.*;
import static org.tinygroup.tinysqldsl.Update.*;

import java.util.List;

import org.springframework.stereotype.Component;
import org.tinygroup.tinysqldsl.Delete;
import org.tinygroup.tinysqldsl.Insert;
import org.tinygroup.tinysqldsl.Select;
import org.tinygroup.tinysqldsl.Update;
import org.tinygroup.tinysqldsl.Pager;
import org.tinygroup.tinysqldsl.extend.MysqlSelect;

import com.xnck.maventest.entity.User;

@Component
public class UserDaoImpl extends BaseOneDao {

	public User insertUser(User user) {
		Insert insert = insertInto(USER).values(
				USER.USERID.value(user.getUserId()),
				USER.USERNAME.value(user.getUserName()));
		dslSession.execute(insert);
		return user;
	}

	public int updateUser(User user) {
		Update update = update(USER).set(
				USER.USERNAME.value(user.getUserName())).where(
				USER.USERID.eq(user.getUserId()));
		return dslSession.execute(update);
	}

	public int deleteUser(String pk) {
		Delete delete = delete(USER).where(USER.USERID.eq(pk));
		return dslSession.execute(delete);
	}

	public int deleteUsers(Object... pks) {
		Delete delete = delete(USER).where(USER.USERID.in(pks));
		return dslSession.execute(delete);
	}

	@SuppressWarnings({"rawtypes" })
	public User getUserById(String pk) {
		Select select = selectFrom(USER).where(USER.USERID.eq(pk));
		return dslSession.fetchOneResult(select, User.class);
	}

	@SuppressWarnings({"rawtypes" })
	public List<User> queryUsers(User user) {
		if(user==null){
			user=new User();
		}
		Select select = selectFrom(USER).where(
				and(
				USER.USERNAME.eq(user.getUserName())));
		return dslSession.fetchList(select, User.class);
	}

	@SuppressWarnings({"rawtypes" })
	public Pager<User> queryUsersForPage(int start,int limit ,User user) {
		if(user==null){
			user=new User();
		}
		Select select = MysqlSelect.selectFrom(USER).where(
				and(
				USER.USERNAME.eq(user.getUserName())));
		return dslSession.fetchPage(select,start, limit, false, User.class);
	}

}
